const { SuccessModel, isTrue, sleep } = require('../util/util.js');
const path = require('path');
const md5 = require("../util/md5.js");
const fs = require('fs');

const baseDir = path.resolve(__dirname, '../assets/images');
const imgNameList = [];
const uploadController = async (req, res) => {
    if (req.method === 'POST') {
        const { fileChuck, fileChuckHash, isCompleted, fileHash } = req.body;
        await sleep(500);
        const fileChuckId = md5(fileChuck, fileChuckHash);
        const filePath = path.resolve(baseDir, fileChuckId);

        if (!fs.existsSync(filePath)) {
            imgNameList.push(fileChuckId);
            fs.writeFileSync(filePath, fileChuck);
        }
        if (isTrue(isCompleted) && imgNameList.length > 0) {
            const writeStream = fs.createWriteStream(path.resolve(baseDir, 'merge.jpg'));
            streamMergeRecursive(imgNameList, writeStream);
        }
        return new SuccessModel({
            imgName: fileChuckId
        });
    }
}
/**
 * @description: 将图片文件切片列表通过文件流的方式合并成一个文件，文件合并完成后删除所有的切片。
 * @param {*} imgNameList 图片文件列表
 * @param {*} writeStream 写入流
 * @param {*} deleFileList 需要删除的图片文件列表
 * @return {*}
 */
function streamMergeRecursive(imgNameList, writeStream, deleFileList = []) {
    // TODO:待补充代码
}
function deleFile(imgNameList) {
    imgNameList.forEach(dir => {
        const curPath = path.resolve(baseDir, dir);
        fs.unlinkSync(curPath);
    })
}

module.exports = uploadController;